package org.dudemonkey.thread.p98;

import org.dudemonkey.util.Downloader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 笔记：2020年06月17日22:14:52
 * P98
 * 知识点：保护性暂停
 * jdk中的join、Future即为此特性
 *
 * 个人观点：考察wait与notify的使用
 */
public class GuardedSuspension {
    private static final Logger log = LoggerFactory.getLogger(GuardedSuspension.class);


    public static void main(String[] args) {
        final GuardedObject go = new GuardedObject();
        new Thread(()->{
            log.debug("Waiting ... ");
            Object o = go.get();
            log.debug("Get res : {}",o);
        },"t1").start();

        new Thread(()->{
            String page = Downloader.getPage();
            go.produce(page);
            log.debug("Produce thread produce ...");
        },"t2").start();

    }
}


class GuardedObject {
    private Object response;

    public Object get(){
        /**
         * 自己带坑的地方：下述的synchronized (this)  我第一次写时写的是synchronized (response)
         * this.wait();  第一次写时写的是 response.wait() 均报了null异常
         */
        synchronized (this){
            while (response==null){
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            return response;
        }
    }

    public void produce(Object obj){
        synchronized (this){
            this.response=obj;
            this.notifyAll();
        }
    }
}